package cn.deschen.eshop.auth.filter;

import cn.deschen.eshop.auth.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author hanbin_chen
 * @Description 动态权限过滤器，用于实现基于路径的动态权限过滤
 * @DateTime 2021/1/22 9:43
 * @Version V1.0.0
 */
@Slf4j
@Component
public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {

    @Autowired
    private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;

    @Autowired
    private SecurityProperties securityProperties;

    public DynamicSecurityFilter(DynamicAccessDecisionManager dynamicAccessDecisionManager) {
        super.setAccessDecisionManager(dynamicAccessDecisionManager);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("【权限模块】请求路径url = {}", ((HttpServletRequest) request).getRequestURI());
        // 获取请求路径
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
        // 那些路径直接放行
        //OPTIONS请求直接放行
        if(httpRequest.getMethod().equals(HttpMethod.OPTIONS.toString())){
            filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
            return;
        }
        // 白名单放行
        PathMatcher matcher = new AntPathMatcher();
        for (String ignoreUrl : securityProperties.getBrowser().getIgnoreUrls()) {
            if (matcher.match(ignoreUrl, httpRequest.getRequestURI())) {
                filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
                return;
            }
        }
        // 对其他路径进行鉴权
        //此处会调用AccessDecisionManager中的decide方法进行鉴权操作
        InterceptorStatusToken token = super.beforeInvocation(filterInvocation);
        try {
            filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }

    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return dynamicSecurityMetadataSource;
    }
}
